import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'dart:async';

class LiveControlPage extends StatefulWidget {
  const LiveControlPage({Key? key}) : super(key: key);

  @override
  State<LiveControlPage> createState() => _LiveControlPageState();
}

class _LiveControlPageState extends State<LiveControlPage> with AutomaticKeepAliveClientMixin {
  late final WebViewController _controller;
  String _status = '正在初始化直播控制台...';
  String _currentUrl = '';
  final List<String> _logs = [];
  Timer? _loginCheckTimer;
  bool _isLoggedIn = false;
  bool _pageLoaded = false;
  bool _wasOnLiveControl = false;
  bool _isLogPanelVisible = true;

  @override
  bool get wantKeepAlive => true;

  @override
  void initState() {
    super.initState();
    _currentUrl = 'https://buyin.jinritemai.com/dashboard/live/control';
    _initWebView();
  }

  @override
  void dispose() {
    _loginCheckTimer?.cancel();
    super.dispose();
  }

  void _initWebView() {
    setState(() {
      _logs.add('[${_getTimeString()}] 开始初始化直播控制台...');
    });

    _controller = WebViewController()
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setBackgroundColor(const Color(0x00000000))
      ..setUserAgent('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36')
      ..enableZoom(true)
      ..setNavigationDelegate(
        NavigationDelegate(
          onProgress: (int progress) {
            setState(() {
              _status = '正在加载直播控制台... $progress%';
            });
            print('[LiveControl] 加载进度: $progress%');
          },
          onPageStarted: (String url) {
            setState(() {
              String previousUrl = _currentUrl;
              _currentUrl = url;
              _pageLoaded = false;
              _logs.add('[${_getTimeString()}] 开始加载页面: $url');
              
              // 检测是否从直播控制台页面跳转到其他页面（登录失效）
              if (_wasOnLiveControl && previousUrl.contains('dashboard/live/control') && 
                  !url.contains('dashboard/live/control') && !url.contains('login')) {
                _status = '检测到登录失效，正在跳转到登录页面...';
                _logs.add('[${_getTimeString()}] 登录失效，从直播控制台跳转到了: $url');
                _logs.add('[${_getTimeString()}] 强制跳转到登录页面...');
                print('[LiveControl] 登录失效，强制跳转到登录页面');
                _isLoggedIn = false;
                _wasOnLiveControl = false;
                
                // 强制跳转到登录页面
                Future.delayed(const Duration(milliseconds: 500), () {
                  _controller.loadRequest(Uri.parse('https://buyin.jinritemai.com/mpa/account/login?log_out=1&type=24'));
                });
                return;
              }
              
              if (url.contains('login') || url.contains('passport')) {
                _status = '检测到登录页面，请先登录...';
                _logs.add('[${_getTimeString()}] 跳转到登录页面，需要先登录');
                _isLoggedIn = false;
                _loginCheckTimer?.cancel();
              } else if (url.contains('dashboard/live/control')) {
                _status = '正在加载直播控制台页面...';
                _logs.add('[${_getTimeString()}] 正在加载直播控制台页面');
                _wasOnLiveControl = true;
              } else if (url.contains('buyin.jinritemai.com/dashboard') && !url.contains('live/control')) {
                // 检测到dashboard页面，说明登录成功
                _status = '登录成功，正在跳转到直播控制台...';
                _logs.add('[${_getTimeString()}] 检测到dashboard页面，登录成功！');
                _logs.add('[${_getTimeString()}] 准备跳转到直播控制台...');
                _isLoggedIn = true;
                print('[LiveControl] 登录成功，跳转到直播控制台');
                
                // 跳转到直播控制台
                Future.delayed(const Duration(milliseconds: 1000), () {
                  _controller.loadRequest(Uri.parse('https://buyin.jinritemai.com/dashboard/live/control'));
                });
              }
            });
            print('[LiveControl] 开始加载页面: $url');
          },
          onPageFinished: (String url) {
            setState(() {
              _pageLoaded = true;
              _logs.add('[${_getTimeString()}] 页面加载完成');
              
              if (url.contains('login') || url.contains('passport')) {
                _status = '请登录抖店商家后台';
                _logs.add('[${_getTimeString()}] 请完成商家后台登录');
                _isLoggedIn = false;
              } else if (url.contains('dashboard/live/control')) {
                _status = '直播控制台加载完成';
                _logs.add('[${_getTimeString()}] 直播控制台页面加载完成');
                
                // 启动5秒检测计时器
                _startLoginCheckTimer();
              }
            });
            print('[LiveControl] 页面加载完成: $url');
          },
          onWebResourceError: (WebResourceError error) {
            setState(() {
              _status = '加载错误: ${error.description}';
              _logs.add('[${_getTimeString()}] 错误: ${error.description}');
            });
            print('[LiveControl] 加载错误: ${error.description}');
          },
          onNavigationRequest: (NavigationRequest request) {
            setState(() {
              _logs.add('[${_getTimeString()}] 导航请求: ${request.url}');
            });
            print('[LiveControl] 导航请求: ${request.url}');
            return NavigationDecision.navigate;
          },
        ),
      )
      ..loadRequest(Uri.parse(_currentUrl));
  }

  void _startLoginCheckTimer() {
    _loginCheckTimer?.cancel();
    _loginCheckTimer = Timer(const Duration(seconds: 3), () {
      if (_currentUrl.contains('dashboard/live/control') && !_currentUrl.contains('login')) {
        setState(() {
          _isLoggedIn = true;
          _wasOnLiveControl = true;
          _status = '已登录，直播控制台就绪';
          _logs.add('[${_getTimeString()}] 登录状态确认：已登录成功');
          _logs.add('[${_getTimeString()}] 直播控制台就绪，可以开始操作');
        });
        print('[LiveControl] 3秒内未跳转，确认已登录成功');
      }
    });
  }

  String _getTimeString() {
    final now = DateTime.now();
    return '${now.hour.toString().padLeft(2, '0')}:${now.minute.toString().padLeft(2, '0')}:${now.second.toString().padLeft(2, '0')}';
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return WillPopScope(
      onWillPop: () async {
        // 检查WebView是否可以返回
        if (await _controller.canGoBack()) {
          _controller.goBack();
          setState(() {
            _logs.add('[${_getTimeString()}] 网页返回');
          });
          print('[LiveControl] 执行网页返回');
          return false; // 不退出应用
        }
        return true; // 退出应用
      },
      child: Scaffold(
        appBar: AppBar(
          automaticallyImplyLeading: false,
          title: const Text('直播控制台'),
          backgroundColor: Colors.black87,
          actions: [
            IconButton(
              icon: const Icon(Icons.arrow_back_ios),
              onPressed: () async {
                if (await _controller.canGoBack()) {
                  _controller.goBack();
                  setState(() {
                    _logs.add('[${_getTimeString()}] 网页后退');
                  });
                }
              },
            ),
            IconButton(
              icon: const Icon(Icons.arrow_forward_ios),
              onPressed: () async {
                if (await _controller.canGoForward()) {
                  _controller.goForward();
                  setState(() {
                    _logs.add('[${_getTimeString()}] 网页前进');
                  });
                }
              },
            ),
            IconButton(
              icon: const Icon(Icons.refresh),
              onPressed: () {
                _controller.reload();
                setState(() {
                  _logs.add('[${_getTimeString()}] 刷新页面');
                });
                print('[LiveControl] 刷新页面');
              },
            ),
          ],
        ),
        body: Stack(
        children: [
          WebViewWidget(controller: _controller),
          Positioned(
            top: 10,
            left: 10,
            child: Container(
              padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
              decoration: BoxDecoration(
                color: Colors.black87,
                borderRadius: BorderRadius.circular(20),
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withOpacity(0.3),
                    blurRadius: 6,
                    offset: const Offset(0, 3),
                  ),
                ],
              ),
              child: Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Container(
                    width: 8,
                    height: 8,
                    decoration: BoxDecoration(
                      color: _status.contains('错误') ? Colors.red : 
                             _isLoggedIn ? Colors.green : 
                             Colors.orange,
                      shape: BoxShape.circle,
                    ),
                  ),
                  const SizedBox(width: 8),
                  Text(
                    _status,
                    style: const TextStyle(
                      color: Colors.white,
                      fontSize: 12,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                ],
              ),
            ),
          ),
          AnimatedPositioned(
            duration: const Duration(milliseconds: 300),
            curve: Curves.easeInOut,
            bottom: _isLogPanelVisible ? 0 : -150,
            left: 0,
            right: 0,
            child: Container(
              height: 150,
              color: Colors.black.withOpacity(0.9),
              child: Column(
                children: [
                  Container(
                    padding: const EdgeInsets.all(8),
                    decoration: const BoxDecoration(
                      border: Border(
                        bottom: BorderSide(color: Colors.grey),
                      ),
                    ),
                    child: Row(
                      children: [
                        const Icon(Icons.terminal, color: Colors.white, size: 16),
                        const SizedBox(width: 8),
                        const Text(
                          '控制台日志',
                          style: TextStyle(
                            color: Colors.white,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                        const Spacer(),
                        TextButton(
                          onPressed: () {
                            setState(() {
                              _logs.clear();
                            });
                          },
                          child: const Text(
                            '清空',
                            style: TextStyle(color: Colors.grey, fontSize: 12),
                          ),
                        ),
                      ],
                    ),
                  ),
                  Expanded(
                    child: ListView.builder(
                      reverse: true,
                      padding: const EdgeInsets.all(8),
                      itemCount: _logs.length,
                      itemBuilder: (context, index) {
                        final logIndex = _logs.length - 1 - index;
                        return Text(
                          _logs[logIndex],
                          style: TextStyle(
                            color: _logs[logIndex].contains('错误') ? Colors.redAccent :
                                   _logs[logIndex].contains('成功') ? Colors.greenAccent :
                                   Colors.white70,
                            fontSize: 12,
                            fontFamily: 'monospace',
                          ),
                        );
                      },
                    ),
                  ),
                ],
              ),
            ),
          ),
          // 隐藏/显示日志面板的悬浮按钮
          Positioned(
            bottom: _isLogPanelVisible ? 160 : 10,
            right: 10,
            child: AnimatedContainer(
              duration: const Duration(milliseconds: 300),
              child: FloatingActionButton(
                mini: true,
                backgroundColor: Colors.black87,
                onPressed: () {
                  setState(() {
                    _isLogPanelVisible = !_isLogPanelVisible;
                  });
                },
                child: AnimatedRotation(
                  turns: _isLogPanelVisible ? 0.5 : 0,
                  duration: const Duration(milliseconds: 300),
                  child: const Icon(Icons.keyboard_arrow_down, color: Colors.white),
                ),
              ),
            ),
          ),
        ],
      ),
    ),
    );
  }
}